<template>
  <div class="page-wrap">
    <el-card shadow="never">
      <div class="toolbar">
        <el-date-picker v-model="range" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />
        <el-button @click="refresh">刷新</el-button>
      </div>

      <div class="stats">
        <el-statistic title="销售笔数" :value="summary.salesQty" />
        <el-statistic title="销售件数" :value="summary.items" />
        <el-statistic title="销售金额(估)" :value="summary.amount.toFixed(2)" />
      </div>

      <el-card shadow="never" class="mt-12" header="热销商品（Top10）">
        <el-table :data="topProducts" border stripe>
          <el-table-column prop="code" label="编码" width="120" />
          <el-table-column prop="name" label="名称" min-width="160" />
          <el-table-column prop="qty" label="销量" width="100" />
          <el-table-column prop="amount" label="金额(估)" width="120" />
        </el-table>
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStockStore } from '@/stores/stock.js'

const stock = useStockStore()
const range = ref([])
const summary = reactive({ salesQty: 0, items: 0, amount: 0 })
const topProducts = ref([])

onMounted(() => {
  if (!stock.stockList.length) stock.initializeStock()
  refresh()
})

function inRange(dateIso){
  if (!range.value || range.value.length !== 2) return true
  const [start, end] = range.value
  const d = new Date(dateIso).toISOString().slice(0,10)
  return (!start || d >= start) && (!end || d <= end)
}

function refresh(){
  // 以库存历史中 outbound 记录统计，金额用当前售价估算
  const outbound = stock.getStockHistory(null, 'outbound').filter(r => inRange(r.date))
  const byProduct = {}
  outbound.forEach(r => {
    const p = stock.stockList.find(x => x.id === r.productId)
    const price = p ? Number(p.salePrice || 0) : 0
    if (!byProduct[r.productId]) byProduct[r.productId] = { code: p?.code || r.productId, name: p?.name || r.productId, qty: 0, amount: 0 }
    byProduct[r.productId].qty += Number(r.quantity || 0)
    byProduct[r.productId].amount += Number(r.quantity || 0) * price
  })
  const arr = Object.values(byProduct)
  arr.sort((a,b) => b.qty - a.qty)
  topProducts.value = arr.slice(0,10)

  summary.salesQty = outbound.length
  summary.items = arr.reduce((s, x) => s + x.qty, 0)
  summary.amount = arr.reduce((s, x) => s + x.amount, 0)
}
</script>

<style scoped>
.page-wrap { padding: 16px; }
.toolbar { display: flex; gap: 12px; margin-bottom: 12px; align-items: center; }
.stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }
.mt-12 { margin-top: 12px; }
</style>


